package jaoso.framework.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Edgeloner
 * @since 2004-06-23
 */
public class FileUtils
{
    /** DOCUMENT ME! */
    private static Log log = LogFactory.getLog(FileUtils.class);

    /**
     * DOCUMENT ME!
     * 
     * @param dir
     *            DOCUMENT ME!
     */
    public static void removeDir(String dir)
    {
        File f = new File(dir);
        File[] tmps = f.listFiles();

        if (f.exists())
        {
            for (int i = tmps.length; i-- > 0;)
            {
                tmps[i].delete();
            }

            f.delete();
        }
    }

    /**
     * DOCUMENT ME!
     * 
     * @param is
     *            DOCUMENT ME!
     * @param fileName
     *            DOCUMENT ME!
     */
    public static void writeFile(UploadFile file)
    {
        log.info("write file");

        OutputStream os = null;

        if (file.getDirect() != null)
        {
            File f = new File(file.getDirect());

            if (!f.exists())
            {
                f.mkdirs();
            }
        }

        try
        {
            log.info("write file" + file.getDirect() + file.getFileName());
            os = new FileOutputStream(file.getDirect() + file.getFileName());

            int bytesRead = 0;
            byte[] buffer = new byte[8192];

            while ((bytesRead = file.getInputStream().read(buffer, 0, 8192)) != -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e)
        {
            log.error("write file error: file not found \n" + e);
        } catch (IOException e)
        {
            log.error("write file error: " + e);
        }
    }

    public static void downLoadFile(final String url, final UploadFile file)
    {
        URL uri = null;

        try
        {
            uri = new URL(url);
            file.setInputStream(uri.openStream());
            writeFile(file);
        } catch (MalformedURLException e)
        {
            log.error("downLoadFile error: " + e);
        } catch (IOException e)
        {
            log.error("downLoadFile error: " + e);
        }
    }
}